Vue.prototype.$echarts = echarts
var app = new Vue({
    el: '#app',
    created() {

    },
    mounted() {
        this.loadUserInfo();
        this.loadCategoryTags();
        this.loadCategory();
        this.loadSupplier();
        this.loadProduct();
    },
    computed: {},
    methods: {
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                })
                .catch(_ => {
                });
        },
        jumpTr: function (row, event, column) {
            console.log(row.link);
            this.jump(row.link);
        },
        jump: function (url) {
            if (url && url.length > 0) {
                window.open(url, '_blank');
            }

        },
        handleSelect: function (key) {
            console.log("handleSelect: " + key);
            this.activeIndex = key;
            this.handleChangeIndex();
        },
        handleChangeIndex: function () {
            let key = this.activeIndex;
            if (key == '10') {
                this.ctx = 'category_idx';
                this.loadCategory();
                return;
            }
            if (key == '20') {
                this.ctx = 'supplier_idx';
                this.loadSupplier();
                return;
            }
            if (key == '30') {
                this.ctx = 'product_idx';
                this.loadProduct();
                return;
            }
            if (key == '40') {
                this.ctx = 'setting_idx';
                this.loadSetting();
                return;
            }

        },
        onSubmitProductQuery: function () {
            this.loadProduct();
        },
        handleCurrentChange: function (currentPage) {
            let that = this;
            that.currentPage = currentPage;
            console.log("handleCurrentChange : " + this.currentPage)  //点击第几页

            if (that.ctx == 'product_idx') {
                this.loadProduct();
                return;
            }
        },
        handleStockRecordCurrentChange: function (currentPage) {
            let that = this;
            console.log("handleStockRecordCurrentChange : " + that.prsCurrentPage)
            this.loadStockRecord(that.productDetail.id, currentPage);
            return;
        },
        fetchToast: function (response) {
            if(response == null || response.body == null){
                this.$message({
                    message: '请求服务器失败',
                    type: 'error'
                });
                return false;
            }
            if(response.status && response.status == 200 && response.bodyText && response.bodyText.includes('login-card')){
                window.open('/login.html', '_self');
                return false;
            }
            if(response.body.code == 104 || response.body.code == 105){
                this.$message({
                    message: response.body.msg ? response.body.msg : '登录已过期~',
                    type: 'error'
                });
                window.open('/login.html', '_self');
                return false;
            }
            if(response.body.code < 200){
                this.$message({
                    message: response.body.msg ? response.body.msg : '服务器返回未知错误',
                    type: 'error'
                });
                return false;
            }
            return true;
        },
        loadUserInfo: function () {
            let that = this;
            let url = 'api/user';
            this.$http.get(url).then(response => {
                if(!this.fetchToast(response)){
                    return false;
                }
                let data = response.body.data;
                if (data != null) {
                    that.userInfo = data;
                }
            }, err => {
                console.log(err)
            });
        },
        loadSetting: function () {
            let that = this;
            let url = 'api/setting/list';
            this.$http.get(url).then(response => {
                if(!this.fetchToast(response)){
                    return false;
                }
                console.log('loadSetting: ' + response.body);
                let data = response.body.data;
                if (data != null) {
                    that.systemSetting.tagSetting = JSON.stringify(data, null, '\t');
                }
                console.log('loadSetting.tagSetting: ' + that.systemSetting.tagSetting);
            }, err => {
                console.log(err)
            });
        },
        loadProduct: function () {
            let that = this;
            let page = that.currentPage;
            if (this.loading) {
                return;
            }
            let req = {
                "pageNo": page,
                "pageSize": that.pageSize,
                "hasBarCode": that.hasBarCode
            };
            if (that.productQuery.productId != null) {
                req.productId = that.productQuery.productId;
            }
            if (that.productQuery.productName != null) {
                req.productName = that.productQuery.productName;
            }
            if (that.productQuery.barCode != null) {
                req.barCode = that.productQuery.barCode;
            }
            if (that.productQuery.categoryId != null) {
                req.categoryId = that.productQuery.categoryId;
            }

            console.log("loadProduct : " + JSON.stringify(req));

            this.loading = true;
            let url = 'api/product/list';
            this.$http.post(
                url,
                req,
            ).then(response => {
                console.log('productList: ' + response.body);
                if(!this.fetchToast(response)){
                    return false;
                }
                let data = response.body.data;
                if (data != null) {
                    that.totalCount = data.totalCount;
                    that.productList = [];
                    if (data.results != null) {
                        data.results.forEach((item, index) => {
                            that.productList.push(item);
                        });
                    }
                }
                that.loading = false;
            }, err => {
                that.loading = false;
                console.log(err)
            });

        },
        loadProductDetail: function (id, hasStockRecord) {
            if (hasStockRecord == null) {
                hasStockRecord = false;
            }
            let that = this;
            that.productAddInfo = {};
            that.dialogImageUrl = '';
            that.fileList = [];

            let url = 'api/product/detail?productId=' + id;
            this.$http.get(url).then(response => {
                console.log('loadProductDetail: ' + response.body);
                if(!this.fetchToast(response)){
                    return false;
                }
                let data = response.body.data;
                if (data != null) {
                    that.productDetail = data;
                    that.productAddInfo = data;
                    if (hasStockRecord) {
                        that.psrCurrentPage = 1;
                        that.loadStockRecord(that.productDetail.id, 1);
                    }
                    if(data.img){
                        that.dialogImageUrl = data.img;
                        that.fileList.push({name:data.img,url:data.img});
                        console.log(that.fileList)
                    }
                }
            }, err => {
                console.log(err)
            });
        },
        loadStockRecord: function (productId, page) {
            let that = this;
            if (this.psrLoading) {
                return;
            }
            let req = {
                "pageNo": page,
                "pageSize": that.psrPageSize,
                "productId": productId
            };

            console.log("loadStockRecord req: " + JSON.stringify(req));

            this.psrLoading = true;
            let url = 'api/stock/record';
            this.$http.post(
                url,
                req,
            ).then(response => {
                console.log('loadStockRecord res: ' + response.body);
                if(!this.fetchToast(response)){
                    return false;
                }
                let data = response.body.data;
                if (data != null) {
                    that.psrTotalCount = data.totalCount;
                    that.productStockRecordList = [];
                    if (data.results != null) {
                        data.results.forEach((item, index) => {
                            that.productStockRecordList.push(item);
                        });
                    }
                }
                that.psrLoading = false;
            }, err => {
                that.psrLoading = false;
                console.log(err)
            });

        },
        loadCategoryTags: function () {
            let that = this;
            that.categoryOptions = [];
            let url = 'api/category/tags';
            this.$http.get(url).then(response => {
                console.log('loadCategoryTags: ' + response.body);
                if(!this.fetchToast(response)){
                    return false;
                }
                let data = response.body.data;
                if (data != null) {
                    data.forEach((item, index) => {
                        that.categoryOptions.push(item);
                    });
                }
                that.loading = false;
            }, err => {
                that.loading = false;
                console.log(err)
            });
        },
        loadCategory: function () {
            let that = this;
            that.categoryList = [];
            let url = 'api/category/list';
            this.$http.get(url).then(response => {
                console.log(response.body);
                if(!this.fetchToast(response)){
                    return false;
                }
                let data = response.body.data;
                if (data != null) {
                    data.forEach((item, index) => {
                        that.categoryList.push(item);
                    });
                }
                that.loading = false;
            }, err => {
                that.loading = false;
                console.log(err)
            });
        },
        loadSupplier: function () {
            let that = this;
            that.supplierList = [];
            let url = 'api/supplier/list';
            this.$http.get(url).then(response => {
                console.log(response.body);
                if(!this.fetchToast(response)){
                    return false;
                }
                let data = response.body.data;
                if (data != null) {
                    data.forEach((item, index) => {
                        that.supplierList.push(item);
                    });
                }
                that.loading = false;
            }, err => {
                that.loading = false;
                console.log(err)
            });
        },
        handleShowBox: function (boxName) {
            let that = this;
            if (boxName == 'addSupplier') {
                that.supplierAddDrawer = true;
                that.supplierDetail = {
                    id: 0,
                    name: '',
                    ext: ''
                };
            }
            if (boxName == 'addCategory') {
                that.categoryAddDrawer = true;
                that.categoryDetail = {
                    id: 0,
                    name: '',
                    reqTags: []
                };
            }
            if (boxName == 'addProduct') {
                that.productAddDrawer = true;
                that.productAddInfo = {};
                that.dialogImageUrl = '';
                that.fileList = [];
            }
        },
        handleEdit: function (boxName, row) {
            let that = this;
            if (boxName == 'editSupplier') {
                that.$set(that.supplierDetail, 'id', row.id);
                that.$set(that.supplierDetail, 'name', row.name);
                that.$set(that.supplierDetail, 'ext', row.ext);
                that.supplierAddDrawer = true;
            }
            if (boxName == 'editCategory') {
                that.$set(that.categoryDetail, 'id', row.id);
                that.$set(that.categoryDetail, 'name', row.name);
                that.$set(that.categoryDetail, 'reqTags', row.reqTags);
                that.categoryAddDrawer = true;
            }
            if (boxName == 'getProduct') {
                that.loadProductDetail(row.id, true);
                that.productDetailDrawer = true;
            }
            if (boxName == 'addProduct') {
                that.loadProductDetail(row.id, false);
                that.productAddDrawer = true;
            }
        },
        removeStockRecord: function (id) {
            let that = this;
            let url = 'api/stock/record/remove?recordId=' + id;
            this.$http.get(url).then(response => {
                console.log(response.body);
                if(!this.fetchToast(response)){
                    return false;
                }
                let code = response.body.code;
                if (code == 200) {
                    this.$message({
                        message: id + '库存记录撤销成功',
                        type: 'success'
                    });
                    that.loadProductDetail(that.productDetail.id, true);
                }
            }, err => {
                console.log(err)
            });
        },
        handleStockBox: function (boxName, id) {
            let that = this;
            if (boxName == '' || id == '' || id == null || id <= 0) {
                this.$message({
                    showClose: true,
                    message: '参数错误',
                    type: 'error'
                });
                return;
            }
            if (boxName == 'removeStockRecord') {
                that.removeStockRecord(id);
                return;
            }
            if (that.changeStockNum <= 0) {
                this.$message({
                    showClose: true,
                    message: '变更数据不正确',
                    type: 'error'
                });
                return;
            }
            let msgTips = "增加";
            let opType = -1;
            if (boxName == 'plusStock') {
                opType = 1;
            } else if (boxName == 'minusStock') {
                msgTips = "扣减";
                opType = 2;
            }

            let req = {
                "productId": id,
                "stock": that.changeStockNum,
                "opType": opType
            };

            console.log("handleStockBox req: " + JSON.stringify(req));

            let url = 'api/product/updateStock';
            this.$http.post(
                url,
                req,
            ).then(response => {
                console.log('handleStockBox res: ' + response.body);
                if(!this.fetchToast(response)){
                    return false;
                }
                let code = response.body.code;
                if (code == 200) {
                    this.$message({
                        message: msgTips + that.changeStockNum + '个库存操作成功',
                        type: 'success'
                    });
                    that.changeStockNum = 0;
                    that.loadProductDetail(id, true);
                    that.loadProduct();
                }
            }, err => {
                console.log(err)
            });
        },
        onSubmitSupplier: function (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let that = this;
                    let req = {
                        "id": that.supplierDetail.id,
                        "name": that.supplierDetail.name,
                        "ext": that.supplierDetail.ext
                    };

                    console.log("onSubmitSupplier : " + JSON.stringify(req));

                    let url = 'api/supplier/add';
                    this.$http.post(
                        url,
                        req,
                    ).then(response => {
                        if(!this.fetchToast(response)){
                            return false;
                        }
                        let code = response.body.code;
                        if (code == 200) {
                            this.$message({
                                message: '供应商操作成功',
                                type: 'success'
                            });
                            that.loadSupplier();
                            that.supplierDetail = {};
                        }
                    }, err => {
                        console.log(err)
                    });

                } else {
                    return false;
                }
            });
        },
        onSubmitCategory: function (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let that = this;
                    let req = {
                        "id": that.categoryDetail.id,
                        "name": that.categoryDetail.name,
                        "reqTags": that.categoryDetail.reqTags
                    };

                    console.log("onSubmitCategory : " + JSON.stringify(req));

                    let url = 'api/category/add';
                    this.$http.post(
                        url,
                        req,
                    ).then(response => {
                        if(!this.fetchToast(response)){
                            return false;
                        }
                        let code = response.body.code;
                        if (code == 200) {
                            this.$message({
                                message: '品类操作成功',
                                type: 'success'
                            });
                            that.loadCategory();
                            that.categoryDetail = {};
                        }
                    }, err => {
                        console.log(err)
                    });

                } else {
                    return false;
                }
            });
        },
        onSubmitProduct: function (formName) {
            let that = this;
            console.log("dialogImageUrl: " + that.dialogImageUrl)
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let req = {
                        "id": that.productAddInfo.id,
                        "name": that.productAddInfo.name,
                        "barCode": that.productAddInfo.barCode,
                        "price": that.productAddInfo.price,
                        "showPrice": that.productAddInfo.showPrice,
                        "supplierId": that.productAddInfo.supplierId,
                        "categoryId": that.productAddInfo.categoryId,
                        "ext": that.productAddInfo.ext,
                        "img": that.dialogImageUrl
                    };

                    console.log("onSubmitProduct : " + JSON.stringify(req));

                    let url = 'api/product/add';
                    this.$http.post(
                        url,
                        req,
                    ).then(response => {
                        if(!this.fetchToast(response)){
                            return false;
                        }
                        let code = response.body.code;
                        if (code == 200) {
                            this.$message({
                                message: '商品操作成功',
                                type: 'success'
                            });
                            that.productAddInfo = {};
                            that.dialogImageUrl = '';
                            that.fileList = [];
                            that.loadProduct();
                        }
                    }, err => {
                        console.log(err)
                    });

                } else {
                    return false;
                }
            });
        },
        onSubmitSystemSetting: function (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let that = this;
                    let req = {
                        "tagSetting": that.systemSetting.tagSetting
                    };

                    console.log("onSubmitSystemSetting : " + JSON.stringify(req));

                    let url = 'api/setting/update';
                    this.$http.post(
                        url,
                        req,
                    ).then(response => {
                        if(!this.fetchToast(response)){
                            return false;
                        }
                        let code = response.body.code;
                        if (code == 200) {
                            this.$message({
                                message: '系统配置更新成功',
                                type: 'success'
                            });
                            that.loadSetting();
                            this.loadCategoryTags();
                        }
                    }, err => {
                        console.log(err)
                    });

                } else {
                    return false;
                }
            });
        },
        handleRemove: function(file, fileList) {
            console.log(file, fileList);
            this.dialogImageUrl = '';
        },
        handlePictureCardPreview: function(file) {
            console.log(file)
            this.dialogVisible = true;
        },
        handleAvatarSuccess: function (res, file) {
            if(res && res.data){
                this.dialogImageUrl = res.data;
                console.log('handleAvatarSuccess: ' + this.fileList)
            }
        },
    },
    data: {
        config: {
            logo: './static_b/images/logo.png'
        },
        systemSetting: {
            tagSetting: ''
        },
        activeIndex: "30",
        currentPage: 1,
        pageSize: 5,
        totalCount: 0,
        loading: false,

        psrCurrentPage: 1,
        psrPageSize: 3,
        psrTotalCount: 0,
        psrLoading: false,

        ctx: 'product_idx',
        categoryList: [],
        supplierList: [],
        productList: [],
        productStockRecordList: [],
        productQuery: {},
        hasBarCode: false,
        supplierAddDrawer: false,
        categoryAddDrawer: false,
        productDetailDrawer: false,
        productAddDrawer: false,
        supplierDetail: {
            id: 0,
            name: '',
            ext: ''
        },
        supplierRules: {
            name: [
                {required: true, message: '请输入供应商名称', trigger: 'blur'}
            ]
        },
        categoryDetail: {
            id: 0,
            name: '',
            reqTags: []
        },
        categoryRules: {
            name: [
                {required: true, message: '请输入品类名称', trigger: 'blur'}
            ]
        },
        categoryOptions: [],
        productDetail: {},
        productAddInfo: {},
        productRules: {
            name: [
                {required: true, message: '请输入商品名称', trigger: 'blur'}
            ],
            supplierId: [
                {required: true, message: '请选择商品供应商', trigger: 'blur'}
            ],
            categoryId: [
                {required: true, message: '请选择商品品类', trigger: 'blur'}
            ]
        },
        changeStockNum: 0,
        systemSettingRules: {
            tagSetting: [
                {required: true, message: '系统配置不能为空', trigger: 'blur'}
            ]
        },
        dialogImageUrl: '',
        fileList: [],
        dialogVisible: false,
        userInfo: {
            nickname:'',
            canConfig:false
        }
    },
});
